package com.example.finalsystem.Service;

import com.example.finalsystem.Dao.BuyListMapper;
import com.example.finalsystem.Entity.BuyList;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.sql.Timestamp;
import java.util.List;

@Service
public class BuyService {
    private SqlSession openSession()
    {
        String resource = "mybatis-config.xml";
        InputStream is = BuyService.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        return   sessionFactory.openSession(true);
    }
    public Long addBuyList(double totalPrice,String dealId,String buyMethod,String managerPerson)
    {
        BuyList buyList = new BuyList();
        buyList.setBuymethod(buyMethod);
        buyList.setTotalprice(totalPrice);
        buyList.setBuytime(new Timestamp(System.currentTimeMillis()));
        buyList.setFkDealid(dealId);
        buyList.setManageperson(managerPerson);
        SqlSession sqlSession = openSession();
        sqlSession.getMapper(BuyListMapper.class).insert(buyList);
        sqlSession.commit();
        sqlSession.close();
        return   buyList.getBuylistid();
    }
    public List<BuyList> getListOfBuyList(String dealId,int currentPage,int pageSize)
    {
        SqlSession sqlSession = openSession();
        List<BuyList> buyLists =  sqlSession.getMapper(BuyListMapper.class).getListOfBuyList(dealId,(currentPage-1)*pageSize,pageSize);
        sqlSession.close();
        return buyLists;
    }



    public int countBuyList(String dealId)
    {
        SqlSession sqlSession = openSession();
        int i = sqlSession.getMapper(BuyListMapper.class).countBuyList(dealId);
        sqlSession.close();
        return i;
    }
}
